package com.woniuxy.springsecurity.configuration;

import com.woniuxy.springsecurity.filter.JwtAuthentiactionFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Author author
 * @Create 2023-10-26 16:33
 */
//启用授权检查
@EnableGlobalMethodSecurity(prePostEnabled=true)
@Configuration
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {
    //密码加密器
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new  BCryptPasswordEncoder();
    }

    //认证器
    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }


    @Autowired
    JwtAuthentiactionFilter jwtAuthentiactionFilter;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //csrf跨站攻击
                .csrf().disable()
                //禁用Session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                //JWTFilter在Security内置过滤器之前执行
                .addFilterBefore(jwtAuthentiactionFilter, UsernamePasswordAuthenticationFilter.class)
                .authorizeRequests()
                //特殊路径放行,指定特殊路径可以匿名访问
                .antMatchers("/user/login").anonymous()
                .anyRequest().authenticated();
    }
}
